package com.easy.dn.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;

import com.baoyz.actionsheet.ActionSheet;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.dialog.CustomDialog;
import com.easy.dn.app.AppConstant;
import com.easy.dn.app.GlobalApplication;
import com.easy.dn.bean.JobAddressBean;
import com.easy.dn.bean.JobTypeBean;
import com.easy.dn.bean.ProfessionTypeBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

import dn.easy.com.easyto.R;

import static com.easy.dn.ui.usercenter.activity.MyInfomationActivity.REQUEST_CODE_SELECT;

/**
 * 集合了超级多的辣鸡方法
 * 判断中英文
 * 根据服务器返回的字符获取对应的语言
 * 获取地点 获取地点ID对应的地点名称
 * 获取行业 获取行业ID对应的行业名称
 * 获取职位 获取职位ID对应的职位名称
 * ...
 * ...
 * <p>
 * Created by 丁宁
 * on 2017/5/8.
 */

public class DnUtils {


    //判断中英文 true中文
    public static boolean getLocale() {
        String sta = GlobalApplication.getInstance().getResources().getConfiguration().locale.getLanguage();
        if ("zh".equals(sta)) {
            return true;
        } else {
            return false;
        }
    }

    public static View getEmptyView(Context context) {
        return LayoutInflater.from(context).inflate(R.layout.empty_view, null);
    }

    // 根据服务器返回的字符获取对应的语言
    public static String getLanguage(String languageStr) {
        String name = "";
        String[] codes = new String[]{"zh", "en", "de", "fr", "ja", "ko",
                "yue", "pt", "ar", "es", "ru", "hi", "vi", "th", "fa", "ms", "jv", "tr",
                "it", "bn", "mr", "ta", "ur"};
        String[] strs = new String[]{GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Chinese)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_English), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_German)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_French), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Japanese)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_kor), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Cantonese)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Portuguese), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Arabic)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Spaish), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Russian)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_Dard), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_yunan)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_taiguo), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_bosi)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_malai), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_guawa)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_tuerqi), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_edali)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_mengjiala), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_maladi)
                , GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_damier), GlobalApplication.getInstance().getApplicationContext().getString(R.string.search_title_wuerqi)};

        for (int i = 0; i < codes.length; i++) {
            String code = codes[i];
            if (code.equals(languageStr)) {
                name = strs[i];
                break;
            }
        }
        return name;
    }

    /**
     * 调用相机 或者 打开相册 选取图片调用
     *
     * @param activity
     * @param fragmentManager
     * @param count           打开选择,本次允许选择的数量
     */
    public static void showCamera(final Activity activity, FragmentManager fragmentManager, final int count) {
        ActionSheet.createBuilder(activity, fragmentManager)
                .setCancelButtonTitle("取消(Cancel)")
                .setOtherButtonTitles("打开相册(Open Gallery)", "拍照(Camera)")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                ImagePicker.getInstance().setSelectLimit(count);
                                Intent intent1 = new Intent(activity, ImageGridActivity.class);
                                activity.startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                ImagePicker.getInstance().setSelectLimit(count);
                                Intent intent = new Intent(activity, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                activity.startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }
                    }
                })
                .show();
    }

    public static List<JobAddressBean> list;
    public static String dataLsit;

    // 获取初始化数据的中英文文件名称
    public static String getFileName() {
        String fileName;
        String sta = GlobalApplication.getAppContext().getResources().getConfiguration().locale.getLanguage();
        if ("zh".equals(sta)) {
            fileName = "zh_version_data.json";
        } else {
//            fileName = "en_version_data.json";
            fileName = "zh_version_data.json";
        }
        return fileName;
    }

    // 获取城市list
    public static List<JobAddressBean> getAddressList() {
        String jsonData = getJson();
        try {
            Gson gson = new Gson();
            JSONObject data = new JSONObject(jsonData);
            list = new ArrayList<>();
            List<JobAddressBean> hotList = gson.fromJson(data.optJSONArray("chinaHotCityList").toString(), new TypeToken<List<JobAddressBean>>() {
            }.getType());
            List<JobAddressBean> jobAddressBeans = gson.fromJson(data.optJSONArray("chinaCityList").toString(), new TypeToken<List<JobAddressBean>>() {
            }.getType());
            List<JobAddressBean> countryLists = gson.fromJson(data.optJSONArray("countryList").toString(), new TypeToken<List<JobAddressBean>>() {
            }.getType());

            for (JobAddressBean bean : hotList) {
                bean.setIsWhare(AppConstant.ADDRESSHOT);
            }
            for (JobAddressBean bean : jobAddressBeans) {
                bean.setIsWhare(AppConstant.ADDRESSCHINACITY);
            }
            for (JobAddressBean bean : countryLists) {
                bean.setIsWhare(AppConstant.ADDRESSOTHER);
            }
            JobAddressBean jobBean = new JobAddressBean();
            jobBean.setName("中国");
            jobBean.setIsChecked(false);
            jobBean.setCode("100");
            jobBean.setCodeType("100");
            jobBean.setId(100);
            jobBean.setType(100);
            jobBean.setIsDel(100);
            jobBean.setSpelling("zhongguo");
            jobBean.setHotNum("100");
            jobBean.setIsWhare(AppConstant.CHINA);
            jobBean.setChina(true);
            List<JobAddressBean> chinaList = new ArrayList<>();
            chinaList.add(jobBean);

            list.addAll(chinaList);
            list.addAll(hotList);
            list.addAll(jobAddressBeans);
            list.addAll(countryLists);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    // 根据地点ID 获取地点
    public static String getAddressStr(String addressIDs) {
        if (StringUtils.isEmpty(addressIDs)){
            return "";
        }
        String[] str = addressIDs.split(",");
        StringBuffer sb = new StringBuffer();
        List<String> mAddressList = new ArrayList<>();
        String addressStr = "";
        if (list == null) {
            list = getAddressList();
        }
        for (JobAddressBean bean : list) {
            for (int i = 0; i < str.length; i++) {
                if (bean.getCode().equals(str[i])) {
                    mAddressList.add(bean.getName());
                }
            }
        }
        List<String> newAddressList = new ArrayList(new LinkedHashSet(mAddressList));
        for (String address : newAddressList) {
            sb.append(address + " , ");
        }
        if (sb != null && !"".equals(sb.toString())) {
            addressStr = sb.toString().substring(0, sb.length() - 2);
        }
        return addressStr;
    }

    /**
     * 读取assets目录下的json文件
     *
     * @return
     */
    public static String getJson() {
        String fileName = getFileName();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = GlobalApplication.getAppContext().getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataLsit = stringBuilder.toString();
        return dataLsit;
    }

    /**
     * 读取assets目录下的json文件
     * @return
     */
    public static String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = GlobalApplication.getAppContext().getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  stringBuilder.toString();
    }

    public static List<JobTypeBean> mJobTypeList;

    // 获取职位类别数据
    public static List<JobTypeBean> getJobTypeList() {
        JSONObject data = null;
        String json = DnUtils.getJson();
        try {
            data = new JSONObject(json);
            JSONArray tradeList = data.optJSONArray("jobList");
            Gson gson = new Gson();
            mJobTypeList = gson.fromJson(tradeList.toString(), new TypeToken<List<JobTypeBean>>() {
            }.getType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mJobTypeList;
    }

    // 根据职位ID 获取职位名称
    public static String getJobTypeStr(String jobTypeIds) {
        if (StringUtils.isEmpty(jobTypeIds)){
            return "";
        }
        String[] str = jobTypeIds.split(",");
        StringBuffer sb = new StringBuffer();
        String jobTypeStr = "";
        if (mJobTypeList == null) {
            mJobTypeList = getJobTypeList();
        }
        for (JobTypeBean parentBean : mJobTypeList) {
            for (int i = 0; i < str.length; i++) {
                if (parentBean.getId() == Integer.parseInt(str[i])) {
                    sb.append(parentBean.getJobTypeName() + " , ");
                }
            }
        }

        if (sb != null && !"".equals(sb.toString())) {
            jobTypeStr = sb.toString().substring(0, sb.length() - 2);
        }
        return jobTypeStr;
    }

    public static List<ProfessionTypeBean> mProfessionTypeList;

    // 获取行业类别数据
    public static List<ProfessionTypeBean> getProfessionTypeList() {
        JSONObject data = null;
        String json = DnUtils.getJson();
        try {
            data = new JSONObject(json);
            JSONArray tradeList = data.optJSONArray("tradeList");
            Gson gson = new Gson();
            mProfessionTypeList = gson.fromJson(tradeList.toString(), new TypeToken<List<ProfessionTypeBean>>() {
            }.getType());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return mProfessionTypeList;
    }

    // 根据行业ID 获取行业名称
    public static String getProfessionTypeStr(String tradeTypeIds) {
        if (StringUtils.isEmpty(tradeTypeIds)){
            return "";
        }
        String[] str = tradeTypeIds.split(",");
        StringBuffer sb = new StringBuffer();
        String professTypeStr = "";
        if (mProfessionTypeList == null) {
            mProfessionTypeList = getProfessionTypeList();
        }
        for (ProfessionTypeBean parentBean : mProfessionTypeList) {
            for (int i = 0; i < str.length; i++) {
                if (parentBean.getId() == Integer.parseInt(str[i])) {
                    sb.append(parentBean.getTradeTypeName() + " , ");
                }
            }
        }
        if (sb != null && !"".equals(sb.toString())) {
            professTypeStr = sb.toString().substring(0, sb.length() - 2);
        }
        return professTypeStr;
    }

    // 获取工作性质
    public static String getPropertyStr(String propertyIds) {
        if (StringUtils.isEmpty(propertyIds)){
            return "";
        }
        String[] str = propertyIds.split(",");
        StringBuffer sb = new StringBuffer();
        String propertyStr = "";
        for (int i = 0; i < str.length; i++) {
            switch (str[i]) {
                case "0":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_nature0)
                            + " , ");
                    break;
                case "1":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_nature1)
                            + " , ");
                    break;
                case "2":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_nature2)
                            + " , ");
                    break;
                case "3":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_nature3)
                            + " , ");
                    break;
                case "4":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_nature4)
                            + " , ");
                    break;
            }
        }
        if (sb != null && !"".equals(sb.toString())) {
            propertyStr = sb.toString().substring(0, sb.length() - 2);
        }
        return propertyStr;
    }
    //  获取特殊情况名称
    public static String getExceptionalStr(String exceptional) {
        if (StringUtils.isEmpty(exceptional)){
            return "";
        }
        String[] str = exceptional.split(",");
        StringBuffer sb = new StringBuffer();
        String exceptionalStr = "";
        for (int i = 0; i < str.length; i++) {
            switch (str[i]) {
                case "1":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit1)
                            + " , ");
                    break;
                case "2":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit2)
                            + " , ");
                    break;
                case "3":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit3)
                            + " , ");
                    break;
                case "4":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit4)
                            + " , ");
                    break;
                case "5":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit5)
                            + " , ");
                    break;
                case "6":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit6)
                            + " , ");
                    break;
                case "7":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit7)
                            + " , ");
                    break;
                case "8":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.dict_job_fit8)
                            + " , ");
                    break;
            }
        }
        if (sb != null && !"".equals(sb.toString())) {
            exceptionalStr = sb.toString().substring(0, sb.length() - 2);
        }
        return exceptionalStr;
    }
    // 获取身份
    public static String getUserTypeStr(String userTypeIds) {
        if (StringUtils.isEmpty(userTypeIds)){
            return "";
        }
        String[] str = userTypeIds.split(",");
        StringBuffer sb = new StringBuffer();
        String userTypeStr = "";
        for (int i = 0; i < str.length; i++) {
            switch (str[i]) {
                case "0":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.chinese)
                            + " , ");
                    break;
                case "1":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.foreigner)
                            + " , ");
                    break;
                case "2":
                    sb.append(GlobalApplication.getInstance().getApplicationContext().getResources().getString(
                            R.string.overseas_returnee)
                            + " , ");
                    break;
            }
        }
        if (sb != null && !"".equals(sb.toString())) {
            userTypeStr = sb.toString().substring(0, sb.length() - 2);
        }
        return userTypeStr;
    }
    // 过滤header and data
    public static List<ProfessionTypeBean> getFilterProfessionTypeList(List<ProfessionTypeBean> parentList, List<ProfessionTypeBean> childList, String fiterStr) {
        List<ProfessionTypeBean> listBean = new ArrayList<>();
        for (ProfessionTypeBean childBean : childList) {
            if (childBean.getTradeTypeName().toLowerCase().contains(fiterStr.toLowerCase())) {
                for (ProfessionTypeBean parentBean : parentList) {
                    // 根据过滤的child 选出parent
                    if (childBean.getParentId() == parentBean.getId()) {
                        listBean.add(parentBean);
                        listBean.add(childBean);
                    }
                }
            }
        }
        List<ProfessionTypeBean> newList = new ArrayList(new LinkedHashSet(listBean));
        return newList;
    }

    private void getCountryList() {

        String[] countryList;
        if (getLocale()){
            countryList = GlobalApplication.getInstance().getResources().getStringArray(R.array.country_code_list_ch);
        }else
            countryList = GlobalApplication.getInstance().getResources().getStringArray(R.array.country_code_list_en);

        for (int i = 0, length = countryList.length; i < length; i++)
        {
            String[] country = countryList[i].split("\\*");
            String countryName = country[0];
            String countryNumber = country[1];
//            String countrySortKey = characterParserUtil.getSelling(countryName);
//            CountrySortModel countrySortModel = new CountrySortModel(countryName, countryNumber,countrySortKey);
//            String sortLetter = countryChangeUtil.getSortLetterBySortKey(countrySortKey);
//            if (sortLetter == null){
//                sortLetter = countryChangeUtil.getSortLetterBySortKey(countryName);
//            }
//
//            countrySortModel.sortLetters = sortLetter;
//            mAllCountryList.add(countrySortModel);
        }

    }

    /**
     * 写在这里 可以方便以后更改效果
     *
     * @param view
     * @param msg
     */
    public static void showToast(View view, String msg) {
        SnackbarUtils.Short(view, msg).show();
    }

    /**
     * 通用dialog 确定 取消 + title
     *
     * @param mContext
     * @return
     */
    public static CustomDialog.Builder showCustomDialog(Context mContext, String message) {
        return new CustomDialog.Builder(mContext)
                .setDialogView(R.layout.dialog_custom)
                .setText(R.id.message, message)
                .setWidthAndHeight(800, 430)
                .setAnimations(R.style.CenterDialogStyle)
                .setCancelable(true);
    }

    /**
     * 自定义dialog 确定 取消 + title
     * @param mContext
     * @return
     */
    public static CustomDialog.Builder showCustomDialog(Context mContext, String message,int layout) {
        return new CustomDialog.Builder(mContext)

                .setDialogView(layout)
                .setText(R.id.message, message)
                .setAnimations(R.style.CenterDialogStyle)
                .setCancelable(true);
    }
}
